package com.kbbywyclient.ui.activity;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.kbbywyclient.R;
import com.kbbywyclient.app.API;
import com.kbbywyclient.app.App;
import com.kbbywyclient.data.entity.Event;
import com.kbbywyclient.data.entity.MobileLoginOfRegist;
import com.kbbywyclient.data.entity.RegistUser;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.RetrievePwdTwoModule;
import com.kbbywyclient.presenter.RetrievePwdTwoPresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.contarct.RetrievePwdTwoContract;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.CheckFormat;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomToolBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description: 找回密码 第二步
 * Created by FHW
 * on 2017/3/31
 */

public class RetrievePwdTwoActivity extends BaseActivity implements RetrievePwdTwoContract.View {

    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;
    @BindView(R.id.et_mobile)
    EditText et_mobile;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.tv_get_Code)
    TextView tv_get_Code;
    @BindView(R.id.tv_determine)
    TextView tv_determine;

    @Inject
    RetrievePwdTwoPresenter retrievePwdTwoPresenter;

    private String str_mobile = "";
    private String str_code = "";

    private String SalesID = "";

    //验证码
    private final int START_CODE = 1;
    private final int COUNT_CODE = 2;
    private final int END_CODE = 3;
    private boolean isGetCode = false;
    private final int GET_CODE_TIME = 90;
    private int codeTime = 0;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_retrieve_pwd_two;
    }

    @OnClick({R.id.tv_get_Code, R.id.tv_determine})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_get_Code:
                if (!isGetCode) {
//                    retrievePwdTwoPresenter.sendOfCheckMobileCode(str_mobile, "");
                    retrievePwdTwoPresenter.sendMobileCodeNews(str_mobile);
                }
                break;
            case R.id.tv_determine:
                if (isGetCode) {
                    if (!str_code.isEmpty()) {
//                        retrievePwdTwoPresenter.getMobileCodeLoginOfRegist(SalesID, str_mobile, str_code
//                                , StringUtil.getDeviceId(this), API.APPType, PreUtils.getUser(this).getCityName());
                        retrievePwdTwoPresenter.getMobileCodeLoginOfRegist(SalesID, str_mobile, str_code
                                , App.mDeviceToken, API.APPType, PreUtils.getUser(this).getCityName());
                    } else {
                        ToastUtil.showShort("请输入验证码");
                    }
                } else {
                    ToastUtil.showShort("请获取验证码");
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("找回密码第二步");
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        v_toolbar.setLeftViewOnClickLinster(v -> finish());

        et_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                str_code = s.toString();
                if (CheckFormat.isCode(str_code)) {
                    if (isGetCode) {
                        tv_determine.setBackgroundResource(R.drawable.textview_bg_14c095);
                    }
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(et_code.getWindowToken(), 0); //强制隐藏键盘
                    }
                } else {
                    tv_determine.setBackgroundResource(R.drawable.textview_bg_dddddd);
                }
            }
        });

    }

    @Override
    public void initData() {

    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getRetrievePwdTwoComponent(new RetrievePwdTwoModule(this)).inject(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 第一步进来
     *
     * @param retrievePwdOne
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(Event.RetrievePwdOne retrievePwdOne) {
        EventBus.getDefault().removeAllStickyEvents();

        str_mobile = retrievePwdOne.getMobile();
        if (StringUtil.isNotEmpty(str_mobile)) {
            et_mobile.setText(str_mobile.substring(0, 3) + "****" + str_mobile.substring(str_mobile.length() - 4));
        } else {
            ToastUtil.showShort("您未绑定手机号，请联系卡宝宝修改！");
        }

    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case START_CODE:
                    codeTime = GET_CODE_TIME;
                    isGetCode = true;
                    handler.sendEmptyMessage(COUNT_CODE);
                    break;
                case COUNT_CODE:
                    if (codeTime <= 0) {
                        handler.sendEmptyMessage(END_CODE);
                    } else {
                        tv_get_Code.setTextColor(getResources().getColor(R.color.color_757575));
                        ViewUtils.setText(tv_get_Code, codeTime-- + "");
                        handler.sendEmptyMessageDelayed(COUNT_CODE, 1000);
                    }
                    break;
                case END_CODE:
                    isGetCode = false;
                    tv_get_Code.setTextColor(getResources().getColor(R.color.color_14C095));
                    ViewUtils.setText(tv_get_Code, R.string.text_get_code);
                    break;
            }
            return false;
        }
    });

    @Override
    public void loadSucCheck(RegistUser registUser) {

    }

    @Override
    public void loadFaiCheck(String errorMsg) {

    }

    @Override
    public void loadSucCode(RegistUser registUser) {
        SalesID = registUser.getSalesID() + "";
        handler.sendEmptyMessage(START_CODE);
    }

    @Override
    public void loadFaiCode(String errorMsg) {

    }

    @Override
    public void loadSucLoginOfRegist(MobileLoginOfRegist mobileLoginOfRegist) {
        ActivitySkipUtil.skipAnotherActivity(this, RetrievePwdThreeActivity.class);
        EventBus.getDefault().postSticky(new Event.RetrievePwdThree(str_mobile, SalesID, str_code));
    }

    @Override
    public void loadFaiLoginOfRegist(String errorMsg) {

    }
}
